package com.mediacloud.app.newsmodule.fragment.newslist;

import android.text.TextUtils;
import android.util.Log;

import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.basenews.IAdapterRefresh;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragment;
import com.mediacloud.app.newsmodule.fragment.ListPreLoadTool;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.FacadeApi;
import com.mediacloud.app.newsmodule.utils.UniqueUtils;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.mmkv.MMKV;
import com.ty.sdk.Ty;
import com.utils.DeviceUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Hoo on 2017/11/24.
 */

public class CMSNewsListWidthBannerFragment extends BaseNewsListFragment {

    UserInfo userInfo;
    String uuid;
    String uuidTx;
    private final List<ArticleItem> articleListTop = new ArrayList<>();
    private final List<ArticleItem> articleListBody = new ArrayList<>();

    @Override
    public void choosed() {
        super.choosed();
        f5();
    }

    @Override
    protected void getNewsListData() {
        MMKV.defaultMMKV().getBoolean(XKey.FULL_SCREEN, false);
        isSmartRecommend = true;
        matchLBSCataglogId();
        userInfo = UserInfo.getUserInfo(getActivity());
        uuid = DeviceUtils.getUuid(getContext(), false);
        uuidTx = StringUtils.getClient();
        mArticleListData = new ArticleListData();

        if (pageNum == 1) {
            //智能推荐置顶请求
            Observable<JSONObject> dataTop = FacadeApi.getSpiderCmsApiJson(getActivity()).getIntelligentTop(getString(R.string.tenantid));
            dataTop.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<JSONObject>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(JSONObject jsonObject) {
                            if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
                                return;
                            }
                            articleListTop.clear();
                            boolean state = jsonObject.optBoolean("state");
                            if (state) {
                                JSONArray topMeta = jsonObject.optJSONArray("data");
                                if (topMeta != null && topMeta.length() > 0) {
                                    for (int i = 0; i < topMeta.length(); i++) {
                                        JSONObject jsonObject1 = topMeta.optJSONObject(i);
                                        if (jsonObject1 != null) {
                                            try {
                                                ArticleItem item = ArticleItem.parse(jsonObject1);
                                                ShowSwitch showSwitch = new ShowSwitch();
                                                showSwitch.allowShowHitCount = true;
                                                showSwitch.allowShowInteractionCount = false;
                                                showSwitch.allowShowPublishDate = true;
                                                showSwitch.allowShowSource = true;
                                                showSwitch.allowShowComment = true;
                                                item.setmShowSwitch(showSwitch);
                                                if (item.getCmsCustomStyle() == null) {
                                                    item.setAppCustomParams(item.getAppCustomParams());
                                                }
                                                item.isFromTop = true;
                                                item.setLable(null);
                                                articleListTop.add(item);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }

                                }
                            }
                            getIntelligentRecommend();
                        }

                        @Override
                        public void onError(Throwable e) {
                            getIntelligentRecommend();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else if (pageNum > 1) {
            getIntelligentRecommend();
        }
    }

    public int getRandomNumber() {
        if (pageNum > 1) {
            return 20;
        }
        SecureRandom random = new SecureRandom();
        int i = random.nextInt(30-15+1) + 15;// 生成 1-30 之间的随机整数
        if (adaptor != null && adaptor.getListContentData() != null && adaptor.getListContentData().size() <= 200) {
            if (adaptor.getListContentData().size() + i > 200) {
                return 200 - adaptor.getListContentData().size();
            }
        }
        return i;
    }

    private void getIntelligentRecommend() {
        //智能推荐推荐请求
        Observable<JSONObject> dataRecommend;
        if (userInfo.isLogin()) {
            dataRecommend = FacadeApi.getSpiderCmsApiJson(getContext()).getIntelligentRecommend(TextUtils.isEmpty(uuidTx) ? uuid : uuidTx, userInfo.getUserid(), pageNum, getRandomNumber(), false);
        } else {
            dataRecommend = FacadeApi.getSpiderCmsApiJson(getContext()).getIntelligentRecommend(TextUtils.isEmpty(uuidTx) ? uuid : uuidTx, pageNum, getRandomNumber(), false);
        }
        dataRecommend.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
                            return;
                        }
                        mXSmartRefreshLayout.finishRefresh();
                        if (pageNum == 1) {
                            articleListBody.clear();
                            mArticleListData.articleList.clear();
                            mArticleListData.articleList.addAll(articleListTop);
                            if (adaptor instanceof IAdapterRefresh) {
                                ((IAdapterRefresh) adaptor).refresh();
                            }
                        }
                        boolean state = jsonObject.optBoolean("state");
                        if (state) {
                            JSONArray topMeta = jsonObject.optJSONArray("data");
                            if (topMeta != null && topMeta.length() > 0) {
                                for (int i = 0; i < topMeta.length(); i++) {
                                    JSONObject jsonObject1 = topMeta.optJSONObject(i);
                                    if (jsonObject1 != null) {
                                        try {
                                            ArticleItem item = ArticleItem.parse(jsonObject1);
                                            ShowSwitch showSwitch = new ShowSwitch();
                                            showSwitch.allowShowHitCount = true;
                                            showSwitch.allowShowInteractionCount = false;
                                            showSwitch.allowShowPublishDate = true;
                                            showSwitch.allowShowSource = true;
                                            showSwitch.allowShowComment = true;
                                            item.setmShowSwitch(showSwitch);
                                            if (item.getCmsCustomStyle() == null) {
                                                item.setAppCustomParams(item.getAppCustomParams());
                                            }
                                            item.isFromTop = false;
                                            articleListBody.add(item);
                                            mArticleListData.articleList.add(item);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }

                            if (adaptor == null)
                                return;
                            isLoading = false;

                            mXSmartRefreshLayout.finishLoadMore();
                            mXSmartRefreshLayout.setNoMoreData(mArticleListData.articleList.isEmpty());
                            ListPreLoadTool.preLoad(requireContext(), mArticleListData.articleList);
                            if (adaptor.getListContentData() == null) {
                                adaptor.setListContentData(mArticleListData.articleList);
                            } else {
                                if (pageNum == 1) {
                                    List<ArticleItem> listContentData = adaptor.getListContentData();
                                    for (int i = 0; i < listContentData.size(); i++) {
                                        if (listContentData.get(i).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH) {
                                            adaptor.getListContentData().remove(i);
                                        }
                                    }
                                    List<ArticleItem> articleListUnique = UniqueUtils.removeDuplicates(mArticleListData.articleList, articleListBody);
                                    mXSmartRefreshLayout.setHeaderText("智能引擎为您发现" + (articleListUnique.size() - articleListTop.size()) + "条内容");
                                    //下拉刷新时最多显示200条数据
                                    if (adaptor.getListContentData().size() < 200) {
                                        adaptor.getListContentData().addAll(0, mArticleListData.articleList);
                                    }
                                    if (adaptor.getListContentData().size() >= 200) {
                                        adaptor.getListContentData().addAll(0, mArticleListData.articleList);
                                        List list = adaptor.getListContentData().subList(199, adaptor.getListContentData().size() - 1);
                                        adaptor.getListContentData().removeAll(list);
                                    }
                                    ArticleItem item = (ArticleItem) adaptor.getListContentData().get(adaptor.getListContentData().size() - 1);
                                        ArticleItem articleItem = new ArticleItem();
                                        articleItem.setType(TypeX.CUSTOM.SMART_RECOMMENT_REFRESH);
                                        adaptor.getListContentData().add(mArticleListData.articleList.size(), articleItem);

                                } else {
                                    adaptor.getListContentData().addAll(articleListBody);
                                }
                            }
                            adaptor.notifyDataSetChanged();

                            if (hadChoosed) {
                                app_jhapp_home_subtab_content_imp();
                            }
                        }
                        if (adaptor.getListContentData().size() <= 0) {
                            showStateView(TYPE_NO_CONTENT, false);
                        } else {
                            closeStateView();
                        }
                        Log.w("6666666", "list======: " + adaptor.getListContentData().size());
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
                            return;
                        }

                        isLoading = false;
                        pageNum--;
                        mXSmartRefreshLayout.finishRefresh(false);
                        mXSmartRefreshLayout.finishLoadMore();
                        if (e != null && adaptor != null && (adaptor.getListContentData() == null
                                || adaptor.getListContentData().size() == 0)) {
                            showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                        } else if (adaptor != null && (adaptor.getListContentData() == null
                                || adaptor.getListContentData().size() == 0)) {
                            showStateView(TYPE_NO_CONTENT, false);
                        } else
                            closeStateView();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}